import React, { forwardRef } from 'react'
import { IUdFormItem, UdModalForm, http, validators, UdTable } from '@/lib'
import { Empty, Input, Select,Tooltip } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import todoApi from '@/apis/TodoList/index'
import TextArea from 'antd/lib/input/TextArea'
import ProcessList from '@/components/ProcessList'
import approveModal from '@/components/ApproveModal'
import { WithToolbar } from '@/components/PhotoView'
const { Option } = Select

interface IProps {
  record: any
  todoType?: any
  refresh?: any
}
interface IState {
  values?: any
  record?: any
  approverList?: any
  pagination?: any
  loading: boolean
  columns: any[]
}
export default class ApproveForm extends React.Component<IProps, IState> {
  private labelCol: any = { span: 4 }
  private form: WrappedFormUtils
  private record = this.props.record || {}
  private todoType = this.props.todoType
  private refresh = this.props.refresh
  private roleIds = []
  private isLastApprover = false
  private FROZEN_TYPE_ENUM: any = {
    SUSPEND: '暂停发货',
    VIOLATION: '违规',
    OTHER: '其他',
  }
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  constructor(props: IProps, state: IState) {
    super(props)
    this.state = {
      values: {},
      approverList: [],
      record: [],
      loading: false,
      pagination: {},
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          key: 'id',
          render: (text, record, index) => index + 1,
          minWidth: '50px',
        },
        { title: '客户编码', dataIndex: 'dealerCode', minWidth: '40px' },
        { title: '客户名称', dataIndex: 'dealerName', minWidth: '70px' },
        { title: '品牌公司', dataIndex: 'brandName', minWidth: '80px' },
        { title: '配额品项', dataIndex: 'prodBarname', minWidth: '80px' },
        { title: '考核年度', dataIndex: 'stageYear', minWidth: '60px' },
        {
          title: '考核阶段',
          dataIndex: 'stageName',
          width: 80,
          render: (text, record) => {
            return (
              <Tooltip title={record.stageName}>
                <div style={{ width: '80px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.stageName}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '冻结原因',
          dataIndex: 'frozenType',
          render: (text, record, index) => {
            return this.FROZEN_TYPE_ENUM[record.frozenType]
          },
        },
      ],
    }
  }
  componentDidMount() {
    this.getFromDetail()
    if (this.todoType === 1) {
      this.getNextApprover()
    }
  }

  private getFromDetail = () => {
    const {
      record: { traceCode: businessKey, brandCode },
    } = this.props
    let params = { businessKey, brandCode }
    http.get(todoApi.getFreezeDetailApproveDetail, { params }).then(res => {
      let { data } = res
      let values = { ...data }
      if (values.frozenStatus === 1) {
        values.frozenStatusText = '冻结'
      } else if (values.frozenStatus === 0) {
        values.frozenStatusText = '解冻'
      }
      values.planTypeText = this.PLAN_TYPE_ENUM[values.planType]
      values.frozenTypeText = this.FROZEN_TYPE_ENUM[values.frozenType]
      this.setState({
        values,
        record: values,
        pagination: {
          current: 1,
          pageSize: 5,
          total: values?.['quotaApplyDetails'].length ?? 0,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '20', '30', '40'],
          showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        },
      })
    })
  }

  private getNextApprover = async () => {
    try {
      const approverRoles = await http.get(todoApi.getFreezeNextApprove, { params: { taskId: this.record.taskDefId } })
      if (approverRoles.data && approverRoles.data[0] && approverRoles.data[0]?.roleIds?.length > 0) {
        this.roleIds = approverRoles.data[0].roleIds
        const params = { ids: approverRoles.data[0].roleIds }
        const nextApprover = await http.post(todoApi.NextApproverList, params)
        const approverList = nextApprover.data.map(({ id: value, realName: title }) => ({ value, title }))
        this.setState({ approverList })
      } else {
        this.isLastApprover = true
      }
    } catch {}
  }

  private onOk = e => {
    const modalItems = !this.isLastApprover
      ? [
          {
            id: 'approveUserIds',
            label: '下一审批人',
            rules: [validators.required],
            render: () => {
              return (
                <Select mode="multiple" showSearch={true} optionFilterProp="children">
                  {this.state.approverList.map(item => (
                    <Option key={item.value} value={item.value}>
                      {item.title}
                    </Option>
                  ))}
                </Select>
              )
            },
          },
        ]
      : []
    approveModal({
      e,
      modalItems,
      taskId: this.record.taskDefId,
      roleIds: this.roleIds,
      refresh: this.refresh,
      todoType: this.todoType,
    })
  }
  render() {
    const { values, pagination, record, columns } = this.state
    let items: IUdFormItem[] = [
      { label: '计划类型', id: 'planTypeText', render: () => <Input readOnly /> },
      {
        label: '申请类型',
        id: 'frozenStatusText',
        render: () => <Input readOnly />,
      },
      {
        label: '冻结原因',
        id: 'frozenTypeText',
        render: () => <Input readOnly />,
      },
      { label: '备注信息', id: 'remark', render: <TextArea rows={3} readOnly={true} /> },
      {
        label: '申请文件',
        id: 'files',
        render: (
          <>
            <WithToolbar imagesList={values?.['quotaApplyDetailFileRespVoList'] || []} type="processList" />
          </>
        ),
      },
    ]
    return (
      <>
        <UdTable
          rowKey="id"
          columns={
            values.frozenStatus === 0
              ? columns
              : columns.filter(item => {
                  return item.dataIndex !== 'frozenType'
                })
          }
          dataSource={values?.['quotaApplyDetails'] || []}
          onChange={paginationOpt => {
            this.setState({ pagination: paginationOpt })
          }}
          pagination={pagination}
        />
        <UdModalForm
          key={Date.now()}
          getForm={form => (this.form = form)}
          labelCol={this.labelCol}
          items={
            values.frozenStatus === 1
              ? items
              : items.filter(item => {
                  return item.id !== 'frozenTypeText'
                })
          }
          values={values}
        />
        <ProcessList record={record} />
      </>
    )
  }
}
